<template>
  <div class="main-content">
    <div class="layout-breadcrumb">
      <Breadcrumb>
        <BreadcrumbItem href="#">广告</BreadcrumbItem>
        <BreadcrumbItem href="#">广告列表</BreadcrumbItem>
        <BreadcrumbItem href="#">发布广告</BreadcrumbItem>
      </Breadcrumb>
    </div>
    <!-- <Card>
            <Steps :current="currentStep">
                <Step title="广告计划" content="填写广告计划"></Step>
                <Step title="优惠券描述" content="完善优惠券描述"></Step>
            </Steps>
        </Card> -->
    <Card style="margin-top:20px;">
      <div class="layout-content" style="margin:15px;">
        <Row>
          <Col span="12">
          <h3>广告信息</h3>
          <div class="line"></div>
          <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="120">
            <FormItem label="推广计划名称" prop="name">
              <Input v-model="formItem.name" placeholder="不超过20个字"></Input>
            </FormItem>
            <FormItem label="计费方式" prop="charging_ways">
              <Radio v-model="formItem.charging_ways">CPC（按点击计费）</Radio>
            </FormItem>
            <FormItem label="广告出价" prop="click_price">
              <Input v-model="formItem.click_price" placeholder="每一次有效点击的付费金额，填写不小于底价">
              <span slot="append">元</span>
              </Input>
            </FormItem>
            <FormItem label="每日预算" prop="day_budget">
              <Input v-model="formItem.day_budget" placeholder="每天消费金额上限，填写必须高于100">
              <span slot="append">元</span>
              </Input>
            </FormItem>
            <FormItem label="投放平台" prop="platform">
              <CheckboxGroup v-model="formItem.platform">
                <Checkbox label="Android"></Checkbox>
                <Checkbox label="IOS"></Checkbox>
              </CheckboxGroup>
            </FormItem>
            <FormItem label="投放日期" prop="date_range">
              <DatePicker v-model="formItem.date_range" type="daterange" confirm placement="bottom-end" placeholder="Select date" size="large"></DatePicker>
            </FormItem>
            <FormItem label="所属行业" prop="industry">
              <Select v-model="formItem.industry" placeholder="请选择所属行业">
                <OptionGroup label="保险">
                  <Option value="出行险">出行险</Option>
                  <Option value="保险-其他">保险-其他</Option>
                </OptionGroup>
                <OptionGroup label="理财">
                  <Option value="借贷">借贷</Option>
                  <Option value="P2P">P2P</Option>
                  <Option value="信用卡">信用卡</Option>
                  <Option value="贵金属">贵金属</Option>
                  <Option value="彩票">彩票</Option>
                  <Option value="夺宝">夺宝</Option>
                  <Option value="理财-其他">理财-其他</Option>
                  <Option value="夺宝（拍卖）">夺宝（拍卖）</Option>
                </OptionGroup>
                <OptionGroup label="出行">
                  <Option value="网约车">网约车</Option>
                  <Option value="OTA">OTA</Option>
                  <Option value="出行-其他">出行-其他</Option>
                </OptionGroup>
              </Select>
            </FormItem>
            <FormItem label="投放地域" prop="area">
              全部地域
            </FormItem>
            <h3>推广链接</h3>
            <div class="line"></div>
            <FormItem label="推广链接" prop="link">
              <Input v-model="formItem.link" placeholder="请输入推广链接">
              <span slot="prepend">http://</span>
              </Input>
            </FormItem>
            <h3>优惠券描述</h3>
            <div class="line"></div>
            <FormItem label="优惠券标题" prop="title">
              <Input v-model="formItem.title" placeholder="不超过20个字"></Input>
            </FormItem>
            <FormItem label="按钮文案" prop="button_text">
              <Input v-model="formItem.button_text" placeholder="不超过20个字"></Input>
            </FormItem>
            <FormItem label="优惠券图片">
              <div class="upload">
                <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                  <template v-if="item.status === 'finished'">
                    <img :src="item.url">
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                  </template>
                  <template v-else>
                    <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                  </template>
                </div>
                <Upload v-show="uploadList.length === 0" ref="upload" :show-upload-list="false" :default-file-list="defaultList" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="handleBeforeUpload" multiple type="drag" name="image" :action="uploadUrl" style="width: 100%;height:200px;line-height: 1;">
                  <div style="display: flex; align-items: center; justify-content: center; width: 100%;height:200px;line-height: 1;">
                    <Icon type="upload" size="40"></Icon>
                    <p>点击上传优惠券素材图片</p>
                  </div>
                </Upload>
                <Modal title="查看图片" v-model="visible">
                  <img :src="imgUrl" v-if="visible" style="width: 100%">
                </Modal>
              </div>
              <Input class="img-input" v-model="formItem.image_url"></Input>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleSubmit('formItem')">完成，提交审核</Button>
              <Button type="ghost" @click="goBack" style="margin-left: 8px">返回</Button>
            </FormItem>
          </Form>
          </Col>
        </Row>
      </div>
    </Card>
  </div>
</template>

<script type="text/ecmascript-6">

export default {
  name: 'order',
  data() {
    return {
      formItem: {
        name: '',
        charging_ways: true,
        click_price: '',
        day_budget: '',
        platform: [],
        date_range: '',
        industry: '',
        link: '',
        title: '',
        button_text: '',
        image_url: ''
      },
      ruleValidate: {
        // name: [
        //   {
        //     required: true,
        //     message: '推广计划名称不能为空',
        //     trigger: 'blur'
        //   }
        // ],
        // charging_ways: [
        //   {
        //     required: true,
        //     message: '计费方式必选',
        //     trigger: 'change'
        //   }
        // ],
        // click_price: [
        //   {
        //     required: true,
        //     message: '广告出价必填',
        //     trigger: 'blur'
        //   }
        // ],
        // day_budget: [
        //   {
        //     required: true,
        //     message: '每日预算必填',
        //     trigger: 'blur'
        //   }
        // ],
        // platform: [
        //   {
        //     required: true,
        //     type: 'array',
        //     min: 1,
        //     message: '至少选择一个',
        //     trigger: 'change'
        //   }
        // ],
        // date_range: [
        //   {
        //     required: true,
        //     // type: 'date',
        //     message: '投放日期必填',
        //     trigger: 'change'
        //   }
        // ],
        // industry: [
        //   {
        //     required: true,
        //     message: '所属行业必填',
        //     trigger: 'change'
        //   }
        // ],
        // link: [
        //   {
        //     required: true,
        //     message: '推广链接必填',
        //     trigger: 'blur'
        //   }
        // ],
        // title: [
        //   {
        //     required: true,
        //     message: '优惠券标题必填',
        //     trigger: 'blur'
        //   }
        // ],
        // button_text: [
        //   {
        //     required: true,
        //     message: '按钮文字必填',
        //     trigger: 'blur'
        //   }
        // ]
      },
      options3: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      currentStep: 0,
      defaultList: [],
      imgUrl: '',
      visible: false,
      uploadList: [],
      uploadUrl: 'http://localhost/tc_rest_api/public/index.php/api/v1/upload'
    };
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },
  methods: {
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.postData();
        } else {
          this.$Message.error('请正确填写表单！');
        }
      });
    },
    postData() {
      let vm = this;
      vm.$Spin.show();
      let params = {
        type: 'post',
        url: 'ad/create?XDEBUG_SESSION_START=15867',
        params: {
          name: vm.formItem.name,
          charging_ways: vm.formItem.charging_ways,
          click_price: vm.formItem.click_price,
          day_budget: vm.formItem.day_budget,
          platform: vm.formItem.platform,
          date_range: vm.formItem.date_range,
          industry: vm.formItem.industry,
          area: '',
          link: vm.formItem.link,
          title: vm.formItem.title,
          button_text: vm.formItem.button_text,
          image_url: vm.formItem.image_url
        },
        sCallback(data) {
          vm.$Spin.hide();
          vm.$Message.success('提交成功');
          vm.$router.push({
            path: '/home/ad'
          });
        },
        eCallback(e) {
          vm.$Message.error(e.data.msg);
        }
      };
      vm.http.request(params);
    },
    goBack() {
      this.$router.back(-1);
    },
    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    },
    handleRemove(file) {
      // 从 upload 实例删除数据
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      let vm = this;
      let simplifiedUploadList = [];

      // 避免上传图片后，又清空图片数组，造成的 img_arr 字段不存在问题
      if (vm.uploadList.length === 0) {
        simplifiedUploadList = '';
      } else {
        for (let i = 0; i < vm.uploadList.length; i++) {
          simplifiedUploadList.push(vm.uploadList[i].response.msg);
        }
      }
      this.formItem.image_url = simplifiedUploadList;
    },
    handleSuccess(res, file) {
      let vm = this;
      let simplifiedUploadList = [];
      file.url = res.msg.url;
      file.name = res.msg.name;

      for (let i = 0; i < vm.uploadList.length; i++) {
        simplifiedUploadList.push(vm.uploadList[i].response.msg);
      }
      this.formItem.image_url = simplifiedUploadList;
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      });
    },
    handleBeforeUpload() {
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Notice.warning({
          title: '最多只能上传 1 张图片。'
        });
      }
      return check;
    }
  }
};
</script>

<style lang="stylus">
.line {
  margin: 20px 0px;
  height: 1px;
  border-bottom: 1px dashed #bdbdbd;
}

.demo-upload-list {
  display: inline-block;
  width: 100%;
  height: 200px;
  text-align: center;
  line-height: 200px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);

  &:hover {
    .demo-upload-list-cover {
      display: block;
    }
  }

  img {
    width: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);

    i {
      color: #fff;
      font-size: 20px;
      cursor: pointer;
      margin: 0 2px;
    }
  }
}

.img-input {
  display: none;
}
</style>


